import * as cc from 'cc';
import { FixedKeyInput } from '../../2d-platform/script/core/FixedKeyInput';
import { InputSampler } from './InputSampler';
import { Recorder } from './Recorder';
import { FixedUpdate } from 'db://assets/component/shadule/FixedUpdate';
const { ccclass, property } = cc._decorator;

@ccclass('PlayerComponent')
export class PlayerComponent extends cc.Component {
    @property
    speed = 60;

    private recording: Recorder = null!;
    private sample: InputSampler = null!;

    private moveDir = cc.v2();
    onLoad() {
        this.sample = new InputSampler(FixedKeyInput.instance);
        this.recording = new Recorder(this.sample, {
            seed: 0,
            fixedDelta: 0,
        });
        console.log('frame index:', FixedUpdate.instance.frameIndex);
        FixedUpdate.instance.addEvent(this.fixedUpdate, this);
    }

    onDestroy() {
        FixedUpdate.instance.removeEvent(this.fixedUpdate, this);
    }

    fixedUpdate(frameIndex: number) {
        this.record(frameIndex);
        this.moveHandle();
    }

    record(tick: number) {
        this.sample.tickSample();
        this.recording.sample(tick);
    }

    moveHandle() {
        this.moveDir = cc.v2();
        if (this.sample.sampler.up) {
            this.moveDir.y = 1;
        }
        if (this.sample.sampler.down) {
            this.moveDir.y = -1;
        }
        if (this.sample.sampler.left) {
            this.moveDir.x = -1;
        }
        if (this.sample.sampler.right) {
            this.moveDir.x = 1;
        }
        if (this.moveDir.length() != 0) {
            this.move();
        }
        if (this.sample.sampler.fire) {
            this.fire();
        }
    }

    private move() {
        const pos = this.node.position;
        this.node.setPosition(
            pos.x + this.moveDir.x * this.speed,
            pos.y + this.moveDir.y * this.speed,
            0,
        );
    }

    fire() {
        let item = this.recording.exportJson();
        cc.sys.localStorage.setItem('save', item);
    }
}
